---
description: "Reference for Nitric's v0 Go library - Send a message to the websocket"
---

# Go - Websocket.Send()

Send a message from the websocket to a connection.

```go
import (
  "context"
  "fmt"

  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  ws, err := nitric.NewWebsocket("public")
  if err != nil {
    return
  }

  ws.Send(context.TODO(), "D28BA458-BFF4-404A", []byte("Hello World"))

  nitric.Run()
}
```

## Parameters

<Properties>
  <Property name="ctx" required type="context">
    The context of the call, used for tracing.
  </Property>
  <Property name="connectionId" required type="string">
    The ID of the connection which should receive the message.
  </Property>
  <Property name="message" required type="[]byte">
    The message that should be sent to the connection.
  </Property>
</Properties>

## Examples

### Broadcasting a message to all connections.

<Note>
  Do not send messages to a connection during it's `connect` callback, if you
  need to acknowledge connection, do so by using a [topic](../topic/topic)
</Note>

```go
import (
  "fmt"

  "github.com/nitrictech/go-sdk/faas"
  "github.com/nitrictech/go-sdk/nitric"
)

func main() {
  ws, err := nitric.NewWebsocket("public")
  if err != nil {
    return
  }

  connections, err := nitric.NewCollection("connections").With(nitric.CollectionEverything...)
  if err != nil {
    return
  }

  // Register a new connection on connect
  ws.On(faas.WebsocketConnect, func(ctx *faas.WebsocketContext, next faas.WebsocketHandler) (*faas.WebsocketContext, error) {
    err := connections.Doc(ctx.Request.ConnectionID()).Set(ctx.Request.Context(), map[string]interface{}{
      "connectionId": ctx.Request.ConnectionID(),
    })
    if err != nil {
      return ctx, err
    }

    return next(ctx)
  })

  // Remove a registered connection on disconnect
  ws.On(faas.WebsocketDisconnect, func(ctx *faas.WebsocketContext, next faas.WebsocketHandler) (*faas.WebsocketContext, error) {
    err := connections.Doc(ctx.Request.ConnectionID()).Delete(ctx.Request.Context())
    if err != nil {
      return ctx, err
    }

    return next(ctx)
  })

  // Broadcast message to all the registered websocket connections
  ws.On(faas.WebsocketMessage, func(ctx *faas.WebsocketContext, next faas.WebsocketHandler) (*faas.WebsocketContext, error) {
    connectionStream, err := connections.Query().Stream(ctx.Request.Context())
    if err != nil {
      return ctx, err
    }

    for {
      res, err := connectionStream.Next()
      if err != nil {
        break // reached the end of the documents
      }

      connectionId, ok := res.Content()["connectionId"].(string)
      if !ok {
        continue
      }

      err = ws.Send(ctx.Request.Context(), connectionId, ctx.Request.Data())
      if err != nil {
        return ctx, err
      }
    }

    return next(ctx)
  })

  nitric.Run()
}
```
